package com.pda.smallbug.myapplication;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanDevice;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.pda.smallbug.myapplication.httpDomain.MainHttp;
import com.pda.smallbug.myapplication.httpDomain.NextHttp;
import com.pda.smallbug.myapplication.httpDomain.ResetHttp;
import com.pda.smallbug.myapplication.httpDomain.SendData;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class NextActivity extends Activity {
    private final static String SCAN_ACTION = "scan.rcv.message";
    private RecyclerView recyclerView;
    private NextAdapter adapter;
    private List<NextHttp.NextData> data;
    private ImageView back;
    private ScanDevice sm;
    private Button zancun,tijiao;
    private String fbillno;
    private AlertDialog dialog;
    private EditText editText;
    private AlertDialog dialog2;
    private EditText editText2;
    private DecimalFormat fnum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);
        fnum  =   new DecimalFormat("##0.00");
        sm = new ScanDevice();
        sm.setOutScanMode(0);
        sm.setScanLaserMode(4);
        sm.setScanVibrate();
        sm.setScanBeep();
        sm.openScan();

        findViewById(R.id.title).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        back=(ImageView)findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        zancun=(Button)findViewById(R.id.zancun);
        zancun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                zancun();
            }
        });
        tijiao=(Button)findViewById(R.id.tijiao);
        tijiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tijiao();
            }
        });
        recyclerView=(RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(NextActivity.this,LinearLayoutManager.VERTICAL,false));
        adapter=new NextAdapter(NextActivity.this);
        recyclerView.setAdapter(adapter);
        fbillno=getIntent().getStringExtra("id");

        View view=getLayoutInflater().inflate(R.layout.dialog,null);
        Button tiaoguo = (Button) view.findViewById(R.id.tiaoguo);
        Button queding = (Button) view.findViewById(R.id.queding);
        editText2=(EditText)view.findViewById(R.id.editText2);
        final Button xiugai = (Button) view.findViewById(R.id.xiugai);
        editText = (EditText) view.findViewById(R.id.editText);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().isEmpty()){
                    editText2.setText("");
                }else {
                    editText2.setText(fnum.format(Integer.parseInt(charSequence.toString())*currentRatio));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        xiugai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!editText2.isEnabled()){
                    editText2.setEnabled(true);
                }
            }
        });

        tiaoguo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (data.get(currentPosition).getFDqty()<1*currentRatio){
                    dialog2.show();
                }else {
                    data.get(currentPosition).setFDqty(data.get(currentPosition).getFDqty()-1*currentRatio);
                    data.get(currentPosition).setFJqty(data.get(currentPosition).getFJqty()+1*currentRatio);
                    data.get(currentPosition).setfJds(data.get(currentPosition).getfJds()+1);
                 //   data.get(currentPosition).setFcheckqty((int) (data.get(currentPosition).getFcheckqty()+1*currentRatio));
                    adapter.notifyDataSetChanged();
                    dialog.dismiss();
                    ifAll();
                }
            }
        });

        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (editText.getText().toString().isEmpty()){
                    Toast.makeText(NextActivity.this,"请输入批量录入袋数",Toast.LENGTH_SHORT).show();
                }else if (Float.parseFloat(editText2.getText().toString())>  data.get(currentPosition).getFDqty()){
                    Toast.makeText(NextActivity.this,"输入数量*系数（输入公斤数）不能大于待检公斤数",Toast.LENGTH_SHORT).show();
                }else {
                    if (data.get(currentPosition).getFDqty()-Integer.parseInt(editText.getText().toString())*currentRatio<0){
                        dialog2.show();
                    }else {
                        data.get(currentPosition).setFJqty(data.get(currentPosition).getFJqty()+Float.parseFloat(editText.getText().toString())*currentRatio);
                        data.get(currentPosition).setFDqty(data.get(currentPosition).getFDqty()-Float.parseFloat(editText.getText().toString())*currentRatio);
                        data.get(currentPosition).setfJds(data.get(currentPosition).getfJds()+Float.parseFloat(editText.getText().toString()));
                     //   data.get(currentPosition).setFcheckqty((int) (data.get(currentPosition).getFcheckqty()+Integer.parseInt(editText.getText().toString())*currentRatio));
                        adapter.notifyDataSetChanged();
                        dialog.dismiss();
                        ifAll();
                    }
                }
            }
        });

        dialog=new AlertDialog.Builder(this)
                .setView(view)
                .setCancelable(false)
                .create();
      //  dialog.show();

        dialog2=new AlertDialog.Builder(NextActivity.this)
                .setMessage("目前待检公斤数小于系数，是否全部检货？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        data.get(currentPosition).setFJqty(data.get(currentPosition).getFJqty()+data.get(currentPosition).getFDqty());
                        data.get(currentPosition).setFDqty(0);
                        data.get(currentPosition).setfJds(data.get(currentPosition).getfJds()+1);
                        adapter.notifyDataSetChanged();
                        dialog.dismiss();
                        ifAll();
                    }
                })
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialog.dismiss();
                    }
                }).create();
        getData();
    }

    private void getData(){
        RequestParams requestParams=new RequestParams(MyApplication.url+"tools/submit_ajax.ashx?action=getpcdetaillist");
        requestParams.addBodyParameter("fbillno", getIntent().getStringExtra("id"));
        x.http().post(requestParams, new Callback.CacheCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("asd",result);
                Gson gson=new Gson();
                NextHttp http= gson.fromJson(result,NextHttp.class);
                if (http.getStatus()==1){
                    data=http.getData();
                    adapter.update(data);
                }else {
                    Toast.makeText(NextActivity.this,http.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("asd",ex.toString());
                Toast.makeText(NextActivity.this,"网络请求失败",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public boolean onCache(String result) {
                return false;
            }
        });
    }

    private int currentPosition=-1;
    private float currentRatio=1;
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            byte[] barocode = intent.getByteArrayExtra("barocode");
            int barocodelen = intent.getIntExtra("length", 0);
            byte temp = intent.getByteExtra("barcodeType", (byte) 0);
            String  barcodeStr = new String(barocode, 0, barocodelen);
            //    String barcodeStr="04.154.01|山东|15417013";
            String[] a=barcodeStr.split("\\|");
            String b=a[0].replace("\\000026","");
            currentPosition=-1;
            currentRatio=1;
            for (final NextHttp.NextData i:data) {
                if (i.getFNumber().equals(b)&&i.getFCD().equals(a[1])&&i.getFBatchNo().equals(a[2])){
                    currentPosition=data.indexOf(i);
                    if (a.length>=4){
                        currentRatio= Float.parseFloat(a[3]);
                    }
                    i.setFratio(currentRatio);
                    break;
                }
            }

            if (currentPosition>-1){
                if (((float)data.get(currentPosition).getFJqty())==((float) data.get(currentPosition).getFTQty())){
                    Toast.makeText(NextActivity.this,"已经完成该条商品的检货",Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    if (data.get(currentPosition).getFP().equals("是")){
                        editText.setText("");
                        dialog.show();
                    }else if (data.get(currentPosition).getFP().equals("否")){
                        if (data.get(currentPosition).getFDqty()<1*currentRatio){
                            dialog2.show();
                        }else {
                            data.get(currentPosition).setFDqty(data.get(currentPosition).getFDqty()-1*currentRatio);
                            data.get(currentPosition).setFJqty(data.get(currentPosition).getFJqty()+1*currentRatio);
                            data.get(currentPosition).setfJds(data.get(currentPosition).getfJds()+1);
                            // data.get(currentPosition).setFcheckqty((int) (data.get(currentPosition).getFcheckqty()+1*currentRatio));
                            adapter.notifyDataSetChanged();
                            ifAll();
                        }
                    }
                }

            }else {
                Toast.makeText(NextActivity.this,"该商品在待处理列表中不存在，检货不通过",Toast.LENGTH_SHORT).show();
            }
                sm.stopScan();
        }
    };

   @Override
    protected void onPause() {
        super.onPause();
        if(sm != null) {
            sm.stopScan();
            sm.closeScan();
        }
        unregisterReceiver(mScanReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(SCAN_ACTION);

        registerReceiver(mScanReceiver, filter);
    }

    private void zancun(){
        ArrayList<SendData> list=new ArrayList<>();
        for (NextHttp.NextData i:data) {
            if (i.getFcheckqty()>0){
                list.add(new SendData(fbillno,i.getFNumber(),i.getFBatchNo(),i.getFCD(), i.getFJqty(),i.getfJds(),i.getFratio()));
            }
        }
        if (list.size()==0){
            Toast.makeText(NextActivity.this,"本次操作还没有完成任何商品的检货",Toast.LENGTH_SHORT).show();
            return;
        }
        RequestParams requestParams=new RequestParams(MyApplication.url+"tools/submit_ajax.ashx?action=submitbill");
        requestParams.addBodyParameter("fbillno",fbillno);
        Gson gson=new Gson();
        String listJson=gson.toJson(list);
        Log.e("asd",listJson);
        requestParams.addBodyParameter("list",listJson);
        requestParams.addBodyParameter("fstatus", "1");
        x.http().post(requestParams, new Callback.CacheCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("asd",result);
                Gson gson=new Gson();
                ResetHttp http=gson.fromJson(result, ResetHttp.class);
                Toast.makeText(NextActivity.this,http.getMsg(),Toast.LENGTH_SHORT).show();
                if (http.getStatus()==1){
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("asd",ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public boolean onCache(String result) {
                return false;
            }
        });
    }

    private void tijiao(){
        ArrayList<SendData> list=new ArrayList<>();
        for (NextHttp.NextData i:data) {
            if (i.getFDqty()>0){
                Toast.makeText(NextActivity.this,"当前还存在待检商品",Toast.LENGTH_SHORT).show();
                return;
            }
            list.add(new SendData(fbillno,i.getFNumber(),i.getFBatchNo(),i.getFCD(),  i.getFJqty(),i.getfJds(),i.getFratio()));
        }
        RequestParams requestParams=new RequestParams(MyApplication.url+"tools/submit_ajax.ashx?action=submitbill");
        requestParams.addBodyParameter("fbillno",fbillno);
        Gson gson=new Gson();
        String listJson=gson.toJson(list);
        requestParams.addBodyParameter("list",listJson);
        requestParams.addBodyParameter("fstatus", "2");
        x.http().post(requestParams, new Callback.CacheCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson=new Gson();
                ResetHttp http=gson.fromJson(result, ResetHttp.class);
                Toast.makeText(NextActivity.this,http.getMsg(),Toast.LENGTH_SHORT).show();
                if (http.getStatus()==1){
                    EventBus.getDefault().post(new MyEvent(1,""));
                    finish();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public boolean onCache(String result) {
                return false;
            }
        });
    }

    private void ifAll(){
        for (NextHttp.NextData i:data) {
            if (i.getFDqty()>0){
                return;
            }
        }
        new AlertDialog.Builder(NextActivity.this)
                .setTitle("提示")
                .setMessage("当前已全部检验，师傅提交？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        tijiao();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create().show();
    }
}
